#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#define SIZE 2
/*
 *使用互斥锁+条件变量让线程B先打印50-100个数据，再让线程B打印0-49个数据
 */ 

pthread_mutex_t mutex;
pthread_cond_t conditional;
//临界区资源：
int val = 100;

void* thread_startA(void* arg)
{
    pthread_mutex_lock(&mutex);
    while(val != 49){
        pthread_cond_wait(&conditional, &mutex);
    }
    
    std::cout<<"i am thread_startA"<<std::endl;
    while(val >=0 ){
        std::cout<<"i use"<<val<<std::endl;
        val--;
    }
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&conditional);
    return NULL;
}

void* thread_startB(void* arg)
{
    sleep(1);
    pthread_mutex_lock(&mutex);
    while(val < 50){
        pthread_cond_wait(&conditional, &mutex);
    }
    std::cout<<"i am thread_startB"<<std::endl;
    
    while(val >=50 ){
        std::cout<<"i use"<<val<<std::endl;
        val--;
    }
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&conditional); 
    return NULL;
}

int main()
{
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&conditional, NULL);
    pthread_t pt[SIZE];
    int ret = pthread_create(&pt[0], NULL, thread_startA, NULL);
    if(ret != 0){
        perror("pthread_create");
        return 0;
    }
    
    ret = pthread_create(&pt[1], NULL, thread_startB, NULL);
    if(ret != 0){
        perror("pthread_create");
        return 0;
    }

    for(int i=0; i < SIZE; ++i){
        pthread_join(pt[i], NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&conditional);
    return 0;
}
